package com.shigu.admin.common.freemarker;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Version;

/**
 * 基于字符模板的freemarker
 * Created by zhaohongbo on 17/7/12.
 */
public class StringFreemarkerUtil {
    /**
     * 模板解析器
     * @param data
     * @param templateStr
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String parseString(Map<String,Object> data, String templateStr) throws IOException, TemplateException {
        Configuration cfg = new Configuration(new Version("2.3.21"));
        cfg.setTemplateLoader(new StringTemplateLoader(templateStr));
        cfg.setDefaultEncoding("UTF-8");

        Template template = cfg.getTemplate("_default_template_key");

        StringWriter writer = new StringWriter();
        template.process(data, writer);
        return writer.toString();
    }
}
